package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;

import java.net.UnknownHostException;

public class DateHistogramAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        DateHistogramAggregationBuilder dateHistogramAggregationBuilder = AggregationBuilders.dateHistogram("agg")
                .field("publish_time").format("yyyy-MM-dd").dateHistogramInterval(DateHistogramInterval.YEAR);
        SearchResponse searchResponse = transportClient.prepareSearch("test_books")
                        .setSize(0).addAggregation(dateHistogramAggregationBuilder).get();
        Histogram histogram = searchResponse.getAggregations().get("agg");
        for(Histogram.Bucket bucket: histogram.getBuckets()) {
            System.out.println(bucket.getKey() + ":" + bucket.getDocCount());
            //getKey返回的是org.joda.time.DateTime类型
        }

        transportClient.close();
    }

}
